package yxy.game.pm2.active.command.ghost;

import yxy.apple.logger.Logger;
import yxy.cherry.data.script.fomula;
import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.active.module.ActiveModule_神魔卡;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.bean.currency.CurrencyNotEnoughException;
import yxy.game.pm2.bean.currency.CurrencyType;
import yxy.game.pm2.bean.mq.CCReason;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.ActiveMessage;
import yxy.game.pm2.module.CurrencyHandle;

/**
 * 神魔卡_抽将 抽将
 * @author Dell
 *
 */
@MessageType(proto = Command.ActGhostGachaHeroSelect, classtype = ActiveMessage.ActGhostGachaHeroSelectRequest.class)
public class CMD_Active_神魔卡_抽将_Select extends Command<ActiveMessage.ActGhostGachaHeroSelectRequest> {

	private static final Logger logger = Logger.create(CMD_Active_神魔卡_抽将_Select.class);
	
	@Override
	public void execute(MessageSource messageSource, ActiveMessage.ActGhostGachaHeroSelectRequest request) throws Exception {
		String playercode = messageSource.getTag();
		int selectid = request.getId();
		ActiveMessage.ActGhostGachaHeroSelectResponse.Builder response = ActiveMessage.ActGhostGachaHeroSelectResponse.newBuilder();
		
		ActiveModule_神魔卡 am = ActiveModule_神魔卡.get(playercode,false);
		if(am == null) {
			send(messageSource, response, Result.ActNoOpen);
			return;
		}

		if(!am.running()) {
			send(messageSource, response, Result.ActNoOpen);
			return;
		}
		
		if(am.getGhostmap().size() == 0) {
			send(messageSource, response, Result.DataError);
			return;
		}
		
		//首次刷新免费
		if(am.getSelectid() == 0) {
			am.setSelectid(selectid);
			am.set();
			send(messageSource, response, Result.Success);
			return;
		}
		
		int costnum = fomula.神魔抽卡替换心仪武将花费.intValue();
		Currency costcur = Currency.create(CurrencyType.CT_元宝, -1, costnum);

		try {
			new CurrencyHandle().cost(playercode, CCReason.活动_神魔卡, costcur);
			am.setSelectid(selectid);
			am.set();
		} catch (CurrencyNotEnoughException e) {
			send(messageSource, response, new Result(Result.CostFail, e.getType().getNumber(), e.getDataId()));// 消费不足
			return;
		}
		
		send(messageSource, response, Result.Success);
	}

	private void send(MessageSource messageSource, ActiveMessage.ActGhostGachaHeroSelectResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}
